<template>
  <div class="permission-user">
    <h1>用户管理页面</h1>
    <div class="table-container">
      <!-- 添加按钮和搜索框 -->
      <div style="margin-bottom: 20px; display: flex; justify-content: space-between;">
        <el-button @click="showAddForm" class="gradient-button">添加用户</el-button>
        <div>
          <el-input
            v-model="searchKeyword"
            placeholder="请输入用户姓名"
            style="width: 200px; margin-right: 10px;"
            clearable
            @clear="searchUsers"
            @keyup.enter="searchUsers"
            class="search-input"
          />
          <el-button @click="searchUsers" class="gradient-button">搜索</el-button>
        </div>
      </div>

      <el-table :data="userList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="userName" label="用户姓名" width="150" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="email" label="电子邮箱" width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="roleNames" label="用户角色类型" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.roleNames && scope.row.roleNames.length > 0" type="primary">{{ scope.row.roleNames }}</el-tag>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="260">
          <template #default="scope">
            <div style="display: flex; justify-content: center; gap: 5px;">
              <el-button
                size="small"
                @click="showCreateAccountForm(scope.row)"
                class="gradient-button">
                创建账号
              </el-button>
              <el-button
                size="small"
                @click="assignRole(scope.row)"
                class="gradient-button"
                style="margin: 0 5px;">
                分配角色
              </el-button>
              <el-button
                size="small"
                @click="editUser(scope.row)"
                class="gradient-button">
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteUser(scope.row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加用户表单对话框 -->
    <el-dialog title="添加用户" v-model="addFormVisible" width="500px" v-if="dialogType === 'add'">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="addForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择状态">
            <el-option label="在职" :value="1"></el-option>
            <el-option label="离职" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="confirmAdd" class="gradient-button">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户表单对话框 -->
    <el-dialog title="编辑用户" v-model="editFormVisible" width="500px" v-if="dialogType === 'edit'">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="editForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="在职" :value="1"></el-option>
            <el-option label="离职" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="confirmEdit" class="gradient-button">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" v-model="assignRoleDialogVisible" width="500px">
      <el-form :model="assignRoleForm" :rules="assignRoleFormRules" ref="assignRoleFormRef">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="assignRoleForm.userId" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="assignRoleForm.userName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="assignRoleForm.roleId" placeholder="请选择角色">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.roleName"
              :value="role.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignRoleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAssignRole" class="gradient-button">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 创建账号对话框 -->
    <el-dialog title="创建账号" v-model="createAccountDialogVisible" width="500px">
      <el-form :model="createAccountForm" :rules="createAccountFormRules" ref="createAccountFormRef">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="createAccountForm.userId" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="createAccountForm.userName" disabled></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="createAccountForm.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="createAccountForm.password" type="password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createAccountDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCreateAccount" class="gradient-button">确定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>



<script>
import { getUserListAPI, addUserAPI, updateUserStatusAPI, updateUserAPI, deleteUserAPI, assignRoleToUserAPI, getUserRolesAPI, getRoleListAPI, createAccountAPI } from '@/apis/sys'

export default {
  name: 'PermissionUser',
  data() {
    return {
      userList: [],
      allUserList: [], // 保存所有用户数据
      searchKeyword: '', // 搜索关键词
      loading: false,
      dialogType: 'add', // 'add' 或 'edit'
      // 角色列表
      roleList: [],
      // 创建账号表单
      createAccountDialogVisible: false,
      createAccountForm: {
        userId: null,
        userName: '',
        account: '',
        password: ''
      },
      createAccountFormRules: {
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      // 分配角色表单
      assignRoleDialogVisible: false,
      assignRoleForm: {
        userId: null,
        userName: '',
        roleId: null
      },
      assignRoleFormRules: {
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      // 添加表单相关数据
      addFormVisible: false,
      addForm: {
        userName: '',
        phone: '',
        email: '',
        status: 1
      },
      addFormRules: {
        userName: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入电子邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      // 编辑表单相关数据
      editFormVisible: false,
      editForm: {
        id: null,
        userName: '',
        phone: '',
        email: '',
        status: 1
      },
      editFormRules: {
        userName: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入电子邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      detailForm: {
        id: null,
        userName: '',
        phone: '',
        email: '',
        status: 1,
        createTime: '',
        updateTime: '',
        roleNames: ''
      }
    }
  },
  async mounted() {
    await this.fetchUserList()
    await this.fetchRoleList()
  },
  methods: {
    // 显示创建账号表单
    showCreateAccountForm(row) {
      this.createAccountForm = {
        userId: row.id,
        userName: row.userName,
        account: '',
        password: ''
      }
      this.createAccountDialogVisible = true
    },

    // 确认创建账号
    async confirmCreateAccount() {
      this.$refs.createAccountFormRef.validate(async (valid) => {
        if (valid) {
          try {
            // 调用后端接口创建账号
            const res = await createAccountAPI(this.createAccountForm)

            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '账号创建成功!'
              })
              this.createAccountDialogVisible = false
            } else {
              this.$message({
                type: 'error',
                message: res.msg || '账号创建失败'
              })
            }
          } catch (error) {
            console.error('创建账号失败:', error)
            this.$message({
              type: 'error',
              message: '创建账号失败: ' + (error.message || error.msg || '未知错误')
            })
          }
        }
      })
    },

    // 获取角色列表
    async fetchRoleList() {
      try {
        const res = await getRoleListAPI()
        if (res.code === 0) {
          this.roleList = res.data.records || res.data
        }
      } catch (error) {
        console.error('获取角色列表失败:', error)
      }
    },

    // 分配角色
    assignRole(row) {
      this.assignRoleForm = {
        userId: row.id,
        userName: row.userName,
        roleId: null
      }
      this.assignRoleDialogVisible = true
    },

    // 确认分配角色
    async confirmAssignRole() {
      this.$refs.assignRoleFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const requestData = {
              userId: this.assignRoleForm.userId,
              roleId: this.assignRoleForm.roleId
            }

            // 调用后端接口分配角色
            const res = await assignRoleToUserAPI(requestData)

            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '角色分配成功!'
              })
              this.assignRoleDialogVisible = false
              // 重新获取用户列表以更新角色信息
              await this.fetchUserList()
            } else {
              // 取消错误弹窗提醒，仅在控制台输出错误信息
              console.error('角色分配失败:', res.msg || '角色分配失败')
            }
          } catch (error) {
            console.error('分配角色失败:', error)
            // 取消错误弹窗提醒，仅在控制台输出错误信息
          }
        }
      })
    },

    // 搜索用户
    searchUsers() {
      if (!this.searchKeyword.trim()) {
        // 如果搜索关键词为空，则显示所有用户
        this.userList = [...this.allUserList];
        return;
      }

      // 根据用户姓名过滤用户列表
      this.userList = this.allUserList.filter(user =>
        user.userName && user.userName.includes(this.searchKeyword.trim())
      );
    },

    // 显示添加表单
    showAddForm() {
      this.dialogType = 'add'
      this.addFormVisible = true
      // 重置表单数据
      this.addForm = {
        userName: '',
        phone: '',
        email: '',
        status: 1
      }
    },

    // 取消添加
    cancelAdd() {
      this.addFormVisible = false
      this.$refs.addFormRef.resetFields()
    },

    // 确认添加
    confirmAdd() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          try {
            // 调用后端接口添加用户
            await addUserAPI(this.addForm)

            // 添加成功后更新列表
            this.$message({
              type: 'success',
              message: '添加用户成功!'
            })

            // 关闭对话框
            this.addFormVisible = false

            // 重新获取用户列表
            await this.fetchUserList()
          } catch (error) {
            console.error('添加用户失败:', error)
            this.$message({
              type: 'error',
              message: '添加用户失败: ' + (error.message || error.msg || '未知错误')
            })
          }
        }
      })
    },

    // 显示编辑表单
    editUser(row) {
      this.dialogType = 'edit'
      this.editFormVisible = true
      // 初始化表单数据
      this.editForm = {
        id: row.id,
        userName: row.userName,
        phone: row.phone,
        email: row.email,
        status: row.status
      }
    },

    // 取消编辑
    cancelEdit() {
      this.editFormVisible = false
      this.$refs.editFormRef.resetFields()
    },

    // 确认编辑
    confirmEdit() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          try {
            // 调用后端接口更新用户信息
            await updateUserAPI(this.editForm)

            // 更新成功后更新列表
            this.$message({
              type: 'success',
              message: '更新用户信息成功!'
            })

            // 关闭对话框
            this.editFormVisible = false

            // 重新获取用户列表
            await this.fetchUserList()
          } catch (error) {
            console.error('更新用户信息失败:', error)
            this.$message({
              type: 'error',
              message: '更新用户信息失败: ' + (error.message || error.msg || '未知错误')
            })
          }
        }
      })
    },

    async fetchUserList() {
      this.loading = true
      try {
        const res = await getUserListAPI()
        if (res.code === 0) {
          // 获取用户列表后，为每个用户获取角色信息
          const usersWithRoles = []
          for (const user of res.data) {
            const userWithRole = {
              ...user,
              createTime: this.formatDateTime(user.createTime) || '-',
              updateTime: this.formatDateTime(user.updateTime) || '-',
              roleNames: '' // 初始化角色名称为空
            }

            try {
              // 获取用户角色信息
              const roleRes = await getUserRolesAPI(user.id)

              // 根据后端返回的数据格式进行处理
              if (roleRes.code === 0) {
                if (typeof roleRes.data === 'string' && roleRes.data) {
                  // 如果返回的是非空字符串，直接使用
                  userWithRole.roleNames = roleRes.data
                } else if (Array.isArray(roleRes.data) && roleRes.data.length > 0) {
                  // 如果返回的是数组，提取roleName
                  userWithRole.roleNames = roleRes.data.map(role => role.roleName).join(', ')
                } else if (roleRes.data && typeof roleRes.data === 'object' && roleRes.data.roleName) {
                  // 如果返回的是对象，提取roleName
                  userWithRole.roleNames = roleRes.data.roleName
                }
                // 如果没有分配角色，保持roleNames为空字符串
              }
              // 如果获取角色信息失败，保持roleNames为空字符串
            } catch (error) {
              // 出错时确保显示为空，不显示错误提示
              userWithRole.roleNames = ''
            }

            usersWithRoles.push(userWithRole)
          }

          this.allUserList = usersWithRoles
          // 初始化显示所有用户
          this.userList = [...this.allUserList]
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取用户列表失败'
          })
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.$message({
          type: 'error',
          message: '获取用户列表失败: ' + (error.msg || error.message || '未知错误')
        })
      } finally {
        this.loading = false
      }
    },

    /**
     * 获取用户的角色名称
     * @param {number} userId - 用户ID
     * @returns {Promise<string>} 角色名称，多个角色用逗号分隔
     */
    async fetchUserRoleNames(userId) {
      try {
        const roleRes = await getUserRolesAPI(userId)
        if (roleRes.code === 0 && roleRes.data) {
          if (Array.isArray(roleRes.data) && roleRes.data.length > 0) {
            // 将角色名称用逗号连接
            return roleRes.data.map(role => role.roleName).join(', ')
          } else if (typeof roleRes.data === 'string') {
            return roleRes.data
          } else if (typeof roleRes.data === 'object' && roleRes.data.roleName) {
            return roleRes.data.roleName
          }
        }
        // 用户未分配角色时返回空字符串而不是"未分配角色"
        return ''
      } catch (error) {
        // 出错时也返回空字符串，不显示错误提示
        return ''
      }
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return ''

      const date = new Date(dateTime)
      if (date.toString() === 'Invalid Date') return ''

      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    getStatusType(status) {
      switch (status) {
        case 0:
          return 'danger'
        case 1:
          return 'success'
        default:
          return 'info'
      }
    },
    getStatusText(status) {
      switch (status) {
        case 0:
          return '离职'
        case 1:
          return '在职'
        default:
          return '未知'
      }
    },
    toggleStatus(row) {
      // 准备发送到后端的数据
      const requestData = {
        id: row.id,
        status: row.status === 1 ? 0 : 1 // 切换状态：在职(1) <-> 离职(0)
      };

      // 调用后端接口更新状态
      updateUserStatusAPI(requestData).then(() => {
        // 后端更新成功后，再更新前端状态
        row.status = requestData.status;

        // 更新时间字段
        const now = new Date();
        const updateTime = now.getFullYear() + '-' +
                        String(now.getMonth() + 1).padStart(2, '0') + '-' +
                        String(now.getDate()).padStart(2, '0') + ' ' +
                        String(now.getHours()).padStart(2, '0') + ':' +
                        String(now.getMinutes()).padStart(2, '0') + ':' +
                        String(now.getSeconds()).padStart(2, '0');
        row.updateTime = updateTime;

        this.$message({
          type: 'success',
          message: `${requestData.status === 1 ? '在职' : '离职'}状态更新成功!`
        });
      }).catch(error => {
        console.error('更新用户状态失败:', error);
        this.$message({
          type: 'error',
          message: '更新用户状态失败: ' + (error.message || error.msg || '未知错误')
        });

        // 如果更新失败，恢复原来的状态
        row.status = row.status === 1 ? 0 : 1;
      });
    },
    deleteUser(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用后端接口删除用户
          await deleteUserAPI({ id: row.id })

          // 从列表中移除
          const index = this.userList.findIndex(item => item.id === row.id)
          if (index > -1) {
            this.userList.splice(index, 1)
          }

          // 同时从完整用户列表中移除
          const allIndex = this.allUserList.findIndex(item => item.id === row.id)
          if (allIndex > -1) {
            this.allUserList.splice(allIndex, 1)
          }

          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        } catch (error) {
          console.error('删除用户失败:', error);
          this.$message({
            type: 'error',
            message: '删除用户失败: ' + (error.message || error.msg || '未知错误')
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style scoped>
.permission-user {
  padding: 20px;
  background-color: #f5f5f5;
}

.permission-user h1 {
  margin-top: 0;
  color: #2c3e50;
}

.table-container {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
}
</style>